package com.hps.notifydemo.bank1.service.impl;

import com.hps.notifydemo.bank1.dao.AccountInfoDao;
import com.hps.notifydemo.bank1.entity.AccountPay;
import com.hps.notifydemo.bank1.model.AccountChangeEvent;
import com.hps.notifydemo.bank1.service.AccountInfoService;
import com.hps.notifydemo.bank1.spring.PayClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author heps
 * @date 2019/12/14 15:50
 */
@Slf4j
@Service
public class AccountInfoServiceImpl implements AccountInfoService {

    @Autowired
    private AccountInfoDao accountInfoDao;

    @Autowired
    private PayClient payClient;

    @Override
    @Transactional
    public void updateAccountBalance(AccountChangeEvent accountChangeEvent) {
        if (accountInfoDao.isExistTx(accountChangeEvent.getTxNo()) > 0) {
            return;
        }
        accountInfoDao.updateAccountBalance(accountChangeEvent.getAccountNo(), accountChangeEvent.getAmount());
        accountInfoDao.addTx(accountChangeEvent.getTxNo());
    }

    @Override
    public AccountPay queryPayResult(String txNo) {
        AccountPay accountPay = payClient.payResult(txNo);
        if ("success".equals(accountPay.getResult())) {
            AccountChangeEvent accountChangeEvent = new AccountChangeEvent();
            accountChangeEvent.setAccountNo(accountPay.getAccountNo());
            accountChangeEvent.setAmount(accountPay.getPayAmount());
            accountChangeEvent.setTxNo(accountPay.getId());
            updateAccountBalance(accountChangeEvent);
        }
        return accountPay;
    }
}
